import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

packageName = ""
className = ""
projectName = ""

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
  SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { generate(it, dir) }
}

def generate(table, dir) {
  className = javaName(table.getName(), true)+""
  table
  packageName = getPackageName(dir)
  projectName = getProjectName(dir)
  new File(dir, className + "Mapper.java").withPrintWriter { out -> out.write((new String(generateContent(out, className).getBytes("UTF-8"))))  }
}


/**
 * 获取包名称
 * @param dir 实体类所在目录
 * @return
 */
def getPackageName(dir) {
  return dir.toString().replaceAll("\\\\", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "").replaceAll("mapper","")
}

def getProjectName(dir) {
  return dir.toString().replaceAll("\\\\", ".")
          .replaceAll("^.*src(\\.main\\.java\\.)?", "")
          .replaceAll("(com\\.pajk\\.)?","")
          .split("\\.")[0]
}

def generateContent(out, className) {

  def sb = new StringBuffer();
  sb.append("package ${packageName}mapper;\n")
  sb.append("\n")

  sb.append("import ${packageName}model.${className}DO;\n")
  sb.append("import com.pajk.${projectName}.client.param.PageQuery;\n")
  sb.append("import org.apache.ibatis.annotations.Param;\n")
  sb.append("\n")
  sb.append("import java.util.List;\n")
  sb.append("\n")

  sb.append("public interface ${className}Mapper {\n")
  sb.append("\n")
  sb.append("\tint insert(${className}DO param);\n");
  sb.append("\n")
  sb.append("\tint update(${className}DO param);\n")
  sb.append("\n")
  sb.append("\tint delete(@Param(\"id\") Long id);\n")
  sb.append("\n")
  sb.append("\t${className}DO getById(@Param(\"id\") Long id);\n")
  sb.append("\n")
  sb.append("\tint countPageQuery(PageQuery param);\n")
  sb.append("\n")
  sb.append("\tList<${className}DO> pageQuery(PageQuery param);\n")
  sb.append("\n")
  sb.append("}\n")
  return sb.toString();
}

def javaName(str, capitalize) {
  def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }
          .join("").replaceAll(/\_/, "")
  capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}